const xml2js = require('xml2js');
const { formatJson } = require('./index');


const xml2json = xml => {

  return new Promise((resolve, reject) => {
    xml2js.parseString(xml, (err, result) => {
      if(err) return reject();
      result = formatJson(result);
      resolve(result);
    });
  });
}

const json2xml = json => new xml2js.Builder().buildObject(json);

const ctxxmlhandle = async (ctx, next) => {

  if(ctx.method === 'POST' && ctx.is('text/xml')) {

    await new Promise((resolve, reject) => {

      let buf = '';
      ctx.req.on('data', chunk => buf += chunk);
      ctx.req.on('end', () => xml2json(buf).then(resolve).catch(reject));
    }).then(result => ctx.req.body = result);

    next();
  } else {
    next();
  }
}

const message = {

  text(msg, content) {// 回复文本消息
    return json2xml({
      xml: {
        ToUserName: msg.FromUserName,
        FromUserName: msg.ToUserName,
        CreateTime: Date.now(),
        MsgType: msg.MsgType,
        Content: content
      }
    });
  }
}

module.exports = { xml2json, json2xml, ctxxmlhandle, message }